require(['../config'],() => {
	require(['request','template','header','greycar','jquery_fly','footer'],(request,template,header,greycar) =>{
	   
	   class Index{
		   constructor() {
		       this.getcakelist().then(() => {
				  this.addtocar()
				  header.calcarcount
                  greycar.calcarcoun()				  
			   })
			   
		   }
		   
		   getcakelist(){
			  
			  return new Promise(resolve =>{
				   request.getCakeList().then(resp => {
				   
				   this.cakes=resp
				  
				  const html = template('cake_list_Template',{
					  list: resp,
					  
				  })
				  $('#shop_list').html(html)
				  resolve()
			  })
			  } )
			
		   }
		   
	addtocar(){
		const _this = this
		 console.log(this.cakes)
		$('.cake_add').on('click',function(e) {
			_this.jqfly(e)
			let id = $(this).parents('tr').data('id')
			let [thecake] = _this.cakes.filter(shop => shop.id == id)
			let cart = localStorage.getItem('cart')
			if(cart) {
				cart = JSON.parse(cart)
				console.log(thecake.id,'thecake.id')
				// 购物车以及有数据
				// console.log(_this.cakes[(id-51)],'_this.cakes[(id-51)]')
				const isExist = cart.some( shop => shop.id === thecake.id)
					console.log(isExist,'isExist')
				if(isExist){
					// 当前商品已经加入购物车
					cart = cart.map(shop => {
						if(shop.id === thecake.id) shop.count++
						return shop
					})
				}else{
				// 	// 当前商品第一次加入购物车
					console.log(cart,'cart')
					cart.push({
						...thecake,
						count:1,
						check:true
					})
				}
				localStorage.setItem('cart',JSON.stringify(cart))
			}
			else{
				console.log(thecake)
				localStorage.setItem('cart',JSON.stringify([{
					...thecake,
					count:1,
					check:true
					}]))
			}
			header.calcarcount()
		})
	}
	
	jqfly(e){

	    		  $('<div class="active"></div>').fly({
	    		  start:{
	    				left: e.clientX,  //开始位置（必填）#fly元素会被设置成position: fixed
	    				top:e.clientY,  //开始位置（必填）
	    			  },
	    			  end:{
	    				left: window.innerWidth-20, //结束位置（必填）
	    				top: 200,  //结束位置（必填）
	    			   
	    			  }
	    
	    		  
	    		  })
	
	 }
		   
	   }
	   new Index()
	})
})

